package com.audiocn.dc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.audiocn.Utils.Log;
import com.audiocn.Utils.Utils;
import com.audiocn.manager.BaseManager;
import com.audiocn.manager.PostersManager;
import com.audiocn.model.BaoBeiDescModel;
import com.audiocn.model.PosterModel;
import com.audiocn.poster.Application;
import com.audiocn.poster.Configs;
import com.audiocn.poster.MsgListDC;
import com.audiocn.poster.PresentEditDC;
import com.audiocn.poster.PresentShowDC;
import com.audiocn.poster.PresentWelDC;
import com.audiocn.poster.R;

/**
 * 逛逛画报详情DC
 */
public class PosterDC extends BaseDC implements OnTouchListener,
		OnItemClickListener, OnItemSelectedListener {

	private Context context;
	Button back;
	TextView title;
	// Button detailBtn;
	public Gallery mGallery;
	public BaseAdapter mGalleryAdapter;
	ProgressDialog progress;
	public static boolean isNotify = true;
	public static boolean isFirst = false;
	float x = 0;
	float y = 0;
	List<PosterModel> data = null;
	List<BaoBeiDescModel> bbs = new ArrayList<BaoBeiDescModel>();

	Animation aOpen;
	Animation aClose_01;
	Animation aClose_02;
	AlphaAnimation aGetout;
	AlphaAnimation aGetin;

	public int sign = -1;

	View v;
	public ListView lv;
	Button open;
	Button close;
	Button save;
	public int position;
	Thread t;

	public MyAdapter mAdapter;
	View getImageLayout = null;

	public PosterDC(Context context, int layoutId, final BaseManager manager) {
		super(context, layoutId, manager);
		
		this.context = context;

		data = new ArrayList<PosterModel>();
		getImageLayout = this.findViewById(R.id.getImageLayout);

		back = (Button) this.findViewById(R.id.poster_back);
		title = (TextView) this.findViewById(R.id.pl_title);
		back.setOnClickListener(this);
		mGallery = (Gallery) this.findViewById(R.id.poster_gallery);
		mGalleryAdapter = new PosterAdapter(context);
		mGallery.setAdapter(mGalleryAdapter);
		mGallery.setOnItemSelectedListener(this);
		mGallery.setOnItemClickListener(this);
		mGallery.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					x = event.getX();
					y = event.getY();
					break;
				case MotionEvent.ACTION_UP:
					if (Math.abs(event.getX() - x) <= 10
							&& Math.abs(event.getY() - y) <= 10) {
						if (back.getVisibility() == VISIBLE) {
							invisibliteBtn();
						} else if (back.getVisibility() == INVISIBLE) {
							visibliteBtn();
						}
					}
					break;
				default:
					break;
				}

				return false;
			}
		});
		aOpen = AnimationUtils.loadAnimation(context, R.anim.scale_animation);
		aClose_01 = AnimationUtils.loadAnimation(context,
				R.anim.scale_animation_03);
		aClose_02 = AnimationUtils.loadAnimation(context,
				R.anim.scale_animation_02);
		progress = new ProgressDialog(context);
		aGetin = new AlphaAnimation(0, 1);
		aGetin.setDuration(700);
		aGetout = new AlphaAnimation(1, 0);
		aGetout.setDuration(700);

		v = this.findViewById(R.id.poster_layout);
		open = (Button) this.findViewById(R.id.poster_open);
		close = (Button) this.findViewById(R.id.poster_close);
		save = (Button) this.findViewById(R.id.poster_savePic);
		close.setVisibility(View.GONE);
		mAdapter = new MyAdapter(context);
		lv = (ListView) this.findViewById(R.id.poster_list);
		lv.setAdapter(mAdapter);
		v.setOnTouchListener(this);
		lv.setOnItemClickListener(this);
		lv.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				mGallery.onTouchEvent(event);
				return false;
			}
		});
		open.setOnClickListener(this);
		close.setOnClickListener(this);
		save.setOnClickListener(this);

		progress.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK
						|| keyCode == KeyEvent.KEYCODE_BACKSLASH) {
					manager.sendEmptyMessage(Configs.STOP_ALL);
				}
				return false;
			}
		});
	}

	@Override
	public void onClicked(View v) {
		switch (v.getId()) {
		case R.id.poster_back:
			manager.sendMessage(manager.obtainMessage(110, 2, 0));
			break;
		case R.id.poster_open:
			openWithAnimation();
			getPic();
			break;
		case R.id.poster_close:
			closeWithAnimation();
			break;
		case R.id.poster_savePic:
			if (data != null && data.size() > this.position) {
//				savePic(data.get(this.position).getImgUrl(),
//						data.get(this.position).getShort_title());
				String desc = data.get(this.position).getDesc();
				String shortTitle = data.get(this.position).getShort_title();
				Intent intent = new Intent(context, PresentEditDC.class);
				intent.putExtra("msg", desc);
				intent.putExtra("title", shortTitle);
				context.startActivity(intent);
			} else {
				Toast.makeText(context, "图片未加载,请加载成功后重试..", 1).show();
			}
			break;
		default:
			break;
		}
	}

	public List<PosterModel> getData() {
		return data;
	}

	public void setData(List<PosterModel> data) {
		this.data = data;
	}

	public void showTipDialog(String msg) {
		Toast.makeText(context, msg, 0).show();
	}

	public void showDialog() {
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setIndeterminate(false);
		progress.setMessage("正在请求数据.....");
		progress.setMax(1000);
		progress.setProgress(1);
		progress.show();
	}

	public void dismissDialog() {
		if (progress.isShowing() == true) {
			progress.dismiss();
		}
	}

	public class PosterAdapter extends BaseAdapter {
		LayoutInflater inflater = null;
		Context context;

		public PosterAdapter(Context context) {
			inflater = LayoutInflater.from(context);
			this.context = context;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.e("getView", "position:" + position);
			View v = null;
			final ViewHolder viewHolder;

			PosterDC.this.position = position;

			if (convertView == null) {
				viewHolder = new ViewHolder();
				v = inflater.inflate(R.layout.poster_list_item, null);
				viewHolder.img = (ImageView) v.findViewById(R.id.pli_img);
				v.setTag(viewHolder);
			} else {
				v = convertView;
				viewHolder = (ViewHolder) v.getTag();
			}
			if (lv != null && (mAdapter != null)) {
				mAdapter.notifyDataSetChanged();
				lv.setAdapter(mAdapter);
			}
			try {
				if (position < data.size()) {

					sign = position;

					if (position < data.size()) {
						data.get(position).setImg(fitSizePic(position));
						System.gc();
						System.gc();
					}
					if (data.get(position).getImg() == null) {
						viewHolder.img.setImageBitmap(BitmapFactory
								.decodeResource(getResources(), Application
										.getLayoutId(R.drawable.default_img)));
						if (Utils.isNetworkValidate()) {
							manager.removeMessages(13);
							manager.sendMessageDelayed(
									manager.obtainMessage(13, position, 0), 500);
						}
					} else {
						dismissGettingImage();
						viewHolder.img.setImageBitmap(data.get(position)
								.getImg());
					}

					if (data.get(position).getBbs() != null
							&& data.get(position).getBbs().size() > 0
							&& data.get(position).getBbs().get(0)
									.getClick_url() != null
							&& !data.get(position).getBbs().get(0)
									.getClick_url().trim().equals("")) {
						if (PosterDC.this.back.getVisibility() == View.VISIBLE) {
							open.setVisibility(View.VISIBLE);
							close.setVisibility(View.GONE);

						} else {
							open.setVisibility(View.GONE);
							close.setVisibility(View.GONE);
						}

					} else {
						open.setVisibility(View.GONE);
						close.setVisibility(View.GONE);
						if (lv != null) {
							lv.removeAllViewsInLayout();
						}
					}
					open.invalidate();
					close.invalidate();

					if ((position - 2) >= 0) {
						if (data.get(position - 2).getImg() != null) {
							data.get(position - 2).getImg().recycle();
							data.get(position - 2).setImg(null);
							System.gc();
						}
					}
					if ((position + 2) < data.size()) {
						if (data.get(position + 2).getImg() != null) {
							data.get(position + 2).getImg().recycle();
							data.get(position + 2).setImg(null);
							System.gc();
						}
					}
					if ((position + 1) < data.size()) {
						if (data.get(position + 1).getImg() == null) {
							data.get(position + 1).setImg(
									fitSizePic(position + 1));
						}
					}
					if ((position - 1) >= 0) {
						if (data.get(position - 1).getImg() == null) {
							data.get(position - 1).setImg(
									fitSizePic(position - 1));
						}
					}
				}
				if (!isNotify && isFirst && (position == (data.size() - 1))) {
				}
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
				System.gc();
				System.gc();
			}
			return v;
		}

	}

	public static final class ViewHolder {
		ImageView img;
	}

	public static final class Holder {
		ImageView img;
		TextView title;
		TextView price;
	}

	public BaseAdapter getPosterAdapter() {
		return mGalleryAdapter;
	}

	public void setPosterAdapter(BaseAdapter posterAdapter) {
		this.mGalleryAdapter = posterAdapter;
	}

	public static Bitmap fitSizePic(byte[] f) {
		Bitmap resizeBmp = null;
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();

			if (f.length > 307200) {
				opts.inSampleSize = 6;
			}

			resizeBmp = BitmapFactory.decodeByteArray(f, 0, f.length, opts);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			System.gc();
			System.gc();
			return null;
		} catch (Exception e) {

		}
		return resizeBmp;
	}

	public Bitmap fitSizePic(int position) {
		if (position >= data.size()) {
			return null;
		}
		Bitmap resizeBmp = null;
		try {
			if (PostersManager.imgs.get(data.get(position).getImgUrl()) == null) {
				return null;
			}
			resizeBmp = BitmapFactory.decodeFile(PostersManager.imgs.get(data
					.get(position).getImgUrl()));
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			System.gc();
			System.gc();
			return null;
		}
		return resizeBmp;
	}

	public class MyAdapter extends BaseAdapter {

		LayoutInflater inflat;

		public MyAdapter(Context context) {
			inflat = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return bbs.size();
		}

		@Override
		public Object getItem(int position) {
			return bbs.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = null;
			Holder holder = null;
			if (convertView == null) {
				holder = new Holder();
				v = inflat.inflate(
						Application.getLayoutId(R.layout.poster_baobei_item),
						null);
				holder.img = (ImageView) v.findViewById(R.id.pbb_pic);
				holder.title = (TextView) v.findViewById(R.id.pbb_title);
				holder.price = (TextView) v.findViewById(R.id.pbb_price);
				v.setTag(holder);
			} else {
				v = convertView;
				holder = (Holder) v.getTag();
			}
			if (position < bbs.size()) {
				if (PostersManager.imgs.containsKey(bbs.get(position)
						.getPic_url())) {
					bbs.get(position).setPic_bitmap(
							BitmapFactory.decodeFile(PostersManager.imgs
									.get(bbs.get(position).getPic_url())));
				}
				if (bbs.get(position).getPic_bitmap() != null
						&& !bbs.get(position).getPic_bitmap().isRecycled()) {
					holder.img
							.setImageBitmap(bbs.get(position).getPic_bitmap());
				} else {
					holder.img.setImageBitmap(BitmapFactory.decodeResource(
							getResources(),
							Application.getLayoutId(R.drawable.default_img)));
				}
				holder.title.setText(Html
						.fromHtml((bbs.get(position).getTitle() == null ? ""
								: bbs.get(position).getTitle())));
				holder.price.setText(bbs.get(position).getPrice());
			}
			return v;
		}
	}

	private void closeWithAnimation() {

		open.setVisibility(View.VISIBLE);
		close.setVisibility(View.GONE);
		v.startAnimation(aClose_01);

		close.setClickable(false);
		open.setClickable(false);

		aClose_01.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				if (t != null && t.isAlive()) {
					t.interrupt();
				}
				v.setVisibility(View.GONE);
				if (lv != null) {
					lv.removeAllViewsInLayout();
				}
				if (bbs != null && bbs.size() > 0) {
					for (int i = 0; i < bbs.size(); i++) {
						if (bbs.get(i).getPic_bitmap() != null) {
							bbs.get(i).getPic_bitmap().recycle();
							bbs.get(i).setPic_bitmap(null);
						}
					}
				}
				System.gc();
				System.gc();
				System.gc();
				close.setClickable(true);
				open.setClickable(true);
			}
		});
	}

	private void openWithAnimation() {
		close.setClickable(false);
		open.setClickable(false);

		open.setVisibility(View.GONE);
		close.setVisibility(View.VISIBLE);
		v.setVisibility(View.VISIBLE);
		v.startAnimation(aOpen);

		aOpen.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				close.setClickable(true);
				open.setClickable(true);
			}
		});
	}

	public void getPic() {
		try {
			if (t != null) {
				t.interrupt();
				t = null;
			}
		} catch (Exception e) {
		}
		t = new Thread() {
			boolean flag = false;

			@Override
			public void run() {
				try {
					Thread.sleep(700);
				} catch (InterruptedException e1) {
				}
				for (int j = 0; j < bbs.size(); j++) {
					if (!flag) {
						if (PostersManager.imgs.containsKey(bbs.get(j)
								.getPic_url())) {
							if (manager.hasMessages(7)) {
								manager.removeMessages(7);
							}
							manager.sendEmptyMessage(7);
							continue;
						}
						URLConnection conn = null;
						InputStream in = null;
						FileOutputStream fos = null;
						try {
							String str = bbs.get(j).getPic_url();
							if (str != null && !str.trim().equals("")) {

								URL uri = new URL(str + "_100x100.jpg");
								conn = uri.openConnection();
								conn.setConnectTimeout(5 * 1000);
								conn.connect();
								in = conn.getInputStream();
								File img = new File(Configs.tlcyImgPath
										+ System.currentTimeMillis() + ".jpg");
								if (img.exists()) {
									img.delete();
								}
								String path = img.getAbsolutePath();
								fos = new FileOutputStream(img);
								if (fos != null && in != null) {
									byte[] b = Utils.getInputData(in);
									if (b != null) {
										fos.write(b);
										fos.flush();
										PostersManager.imgs.put(bbs.get(j)
												.getPic_url(), path);
									}
								}
								if (manager.hasMessages(7)) {
									manager.removeMessages(7);
								}
								manager.sendEmptyMessage(7);
							}
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							try {
								if (in != null) {
									in.close();
									in = null;
								}
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
				super.run();
			}

			@Override
			public void interrupt() {
				flag = true;
				super.interrupt();
			}
		};
		t.start();
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.poster_layout:
			mGallery.onTouchEvent(event);
			break;

		default:
			break;
		}
		return false;
	}

	public void savePic(String url, String name) {
		if (url == null || url.trim().equals("")) {
			Toast.makeText(context, "图片尚未加载,请稍后再试..", 1).show();
			return;
		}
		if (name == null || name.trim().equals("")) {
			name = System.currentTimeMillis() + "";
		}
		String path = PostersManager.imgs.get(url);
		if (path != null && !path.trim().equals("")) {
			try {
				
				
				
				ContentResolver resolver = context.getContentResolver();
				Bitmap bitmap = BitmapFactory.decodeFile(path);
				if (null != bitmap) {
					MediaStore.Images.Media.insertImage(resolver, bitmap, name
							+ "(" + System.currentTimeMillis() + ")" + ".jpg",
							"天籁传音-美图");
					Toast.makeText(context, "已成功保存到图库..", 0).show();
				} else {
					Toast.makeText(context, "保存失败", 0).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(context, "保存失败", 0).show();
			}
		} else {
			Toast.makeText(context, "图片尚未加载,请稍后再试..", 1).show();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (bbs != null && bbs.get(position) != null) {
			manager.sendMessage(manager.obtainMessage(8, bbs.get(position)));
		} else {
			Toast.makeText(context, "请求失败,请重试..", 0).show();
		}

	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view,
			final int position, long id) {
		if (v.getVisibility() == VISIBLE) {
			v.setVisibility(INVISIBLE);
		}
		Log.e("onItemSelected", "position:" + position);
		title.setText(Html.fromHtml(data.get(position).getDesc() == null ? ""
				: data.get(position).getDesc()));
		if (data.get(position).getImg() == null) {
			showGetingImage();
		}
		bbs = data.get(position).getBbs();
		getPic();
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
	}

	/**
	 * 获取图片时显示闪烁动画
	 */
	public void showGetingImage() {
		getImageLayout.setVisibility(View.VISIBLE);
	}

	/**
	 * 图片获取完后动画消失
	 */
	public void dismissGettingImage() {
		getImageLayout.setVisibility(View.GONE);
	}

	public void invisibliteBtn() {
		open.setVisibility(INVISIBLE);
		save.setVisibility(INVISIBLE);
		title.setVisibility(INVISIBLE);
		back.setVisibility(INVISIBLE);
		close.setVisibility(INVISIBLE);
	}

	public void visibliteBtn() {
		save.setVisibility(VISIBLE);
		title.setVisibility(VISIBLE);
		back.setVisibility(VISIBLE);
		showOrHiddenShop();

	}

	public void showOrHiddenShop() {
		if (position < data.size()) {
			if (data.get(position).getBbs() != null
					&& data.get(position).getBbs().size() > 0
					&& data.get(position).getBbs().get(0).getClick_url() != null
					&& !data.get(position).getBbs().get(0).getClick_url()
							.trim().equals("")) {
				if (v.getVisibility() == View.VISIBLE) {
					open.setVisibility(View.GONE);
					close.setVisibility(View.VISIBLE);
				} else {
					open.setVisibility(View.VISIBLE);
					close.setVisibility(View.GONE);
				}

			} else {
				open.setVisibility(View.GONE);
				close.setVisibility(View.GONE);
			}
		}

	}
}
